import logging

from django.contrib.auth import authenticate
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken

logger = logging.getLogger("apps")


# Create your views here.


class LoginView(APIView):

    def post(self, request):
        try:
            username = request.data.get("username")
            password = request.data.get("password")

            if not all([username, password]):
                return Response({
                    "code": 0,
                    "msg": "用户名或密码不能为空"
                })
            user = authenticate(username=username, password=password)
            refresh = RefreshToken.for_user(user)

            if not user:
                return Response({
                    "code": 0,
                    "msg": "用户名或密码错误"
                })

            logger.info(f"{username}登录成功")

            return Response({
                "code": 1,
                "msg": "登录成功",
                "data": {
                    "token": str(refresh.access_token),
                    "redresh": str(refresh),
                    "username": username,
                    "password": password,
                }
            })
        except Exception as e:
            logger.error(f"登录失败{e}")
            return Response({
                "code": 0,
                "msg": "登录失败"
            })
